package com.haoze.nurseapp.service.impl;

import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.UUIDUtil;
import com.haoze.nurseapp.dao.AppUpgraderMapper;
import com.haoze.nurseapp.dao.UserMapper;
import com.haoze.nurseapp.dto.app.AppUpdateQueryDTO;
import com.haoze.nurseapp.dto.app.AppUpgradeAddDTO;
import com.haoze.nurseapp.model.AppUpgradeEntity;
import com.haoze.nurseapp.service.AppUpgradeService;
import com.haoze.nurseapp.vo.app.AppUpdateResponseVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Objects;


/**
 * @author wangze
 * @date 2020-06-08 9:29.
 **/
@Service
public class AppUpgradeServiceImpl implements AppUpgradeService {
	@Resource
	AppUpgraderMapper appUpgraderMapper;

	@Override
	public Result queryAppUpdateInfo(AppUpdateQueryDTO queryDTO) {
		AppUpdateResponseVO appUpdateResponseVO=new AppUpdateResponseVO();
		AppUpgradeEntity appUpgradeInfo=this.appUpgraderMapper.queryAppUpdateInfo(queryDTO.getAppid());
		if(Objects.isNull(appUpgradeInfo)){
			return ResultGenerator.genFailedResult("不存在相关app");
		}
		// 判断是否是最新版本
		if(queryDTO.getVersion().equals(appUpgradeInfo.getAppVersion())){
			return  ResultGenerator.genFailedResult("当前已经是最新版本,无需更新");
		}
		appUpdateResponseVO.setNote(appUpgradeInfo.getNote());
		appUpdateResponseVO.setFilePath(appUpgradeInfo.getFilePath());
		appUpdateResponseVO.setAppid(appUpgradeInfo.getAppId());
		appUpdateResponseVO.setVersion(appUpgradeInfo.getAppVersion());
		return  ResultGenerator.genOkResult(appUpdateResponseVO);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addOrUpdateAppUpgrade(AppUpgradeAddDTO addDto) {
		AppUpgradeEntity appUpgradeInfo=this.appUpgraderMapper.queryAppUpdateInfo(addDto.getAppid());
		// 更新
		if(appUpgradeInfo!=null){
//			if(appUpgradeInfo.getAppVersion().equals(addDto.getVersion())){
//				throw new RuntimeException("版本号不能相同");
//			}
			this.appUpgraderMapper.updateAppUpgrade(addDto.getAppid(),addDto.getVersion(),addDto.getFilePath(),addDto.getNote());
			return;
		}
		//新增
		AppUpgradeEntity appUpgradeEntity=new AppUpgradeEntity();
		appUpgradeEntity.setAppId(addDto.getAppid());
		appUpgradeEntity.setAppType(addDto.getAppType());
		appUpgradeEntity.setDataVersion(1);
		appUpgradeEntity.setAppVersion(addDto.getVersion());
		appUpgradeEntity.setGmtCreate(new Date());
		appUpgradeEntity.setGmtModify(new Date());
		appUpgradeEntity.setUpgradeId(UUIDUtil.randomString());
		appUpgradeEntity.setHospitalId(addDto.getHospitalId());
		appUpgradeEntity.setFilePath(addDto.getFilePath());
		appUpgradeEntity.setNote(addDto.getNote());
		this.appUpgraderMapper.addAppUpgrade(appUpgradeEntity);
	}
}
